package com.oildatacollection.server;

import com.oildatacollection.message.RecvMessage;
import com.oildatacollection.message.protocol.MessageProtocol;
import com.oildatacollection.message.protocol.MessageProtocolModbusImpl;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;
import java.util.List;

@Slf4j
@ChannelHandler.Sharable
public class MessageCodecSharable extends MessageToMessageCodec<ByteBuf, RecvMessage> {
    private final MessageProtocol messageProtocol;

    public MessageCodecSharable() {
        messageProtocol = new MessageProtocolModbusImpl();
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, RecvMessage recvMessage, List<Object> list) throws Exception {
        System.out.println("not impl");
    }

    @Override
    protected void decode(ChannelHandlerContext chanCtx, ByteBuf in, List<Object> out) {
        Pair<RecvMessage, ByteBuf> ret = messageProtocol.decodeMessage(in);
        RecvMessage mess = ret.getKey();
        ByteBuf reply = ret.getValue();
        if (!mess.IsEmpty()) {
            out.add(mess);
        }
        // 发送回复报文
        chanCtx.channel().writeAndFlush(reply);
    }
}

